package com.tulele.vtool.task.async;

import com.tulele.vtool.model.ArticleInfo;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.service.IArticleInfoService;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.utils.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserSaveArticleInfoWxPushAsyncTask {

//    @Autowired
//    private WeixinService weixinService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private IArticleInfoService articleInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    //@Async
    @Async("taskExecutor")
    public void saveArticleInfoWxPushAsyncTask(Integer userId, Integer articleId, String userOpenId,String springProfilesActive) throws Exception {

        //Thread.sleep(1000);
        //设置分享的文章为用户文章
        int finalArticleId = articleId;
        log.info("[UserSaveArticleInfoWxPushAsyncTask]__saveArticleInfoWxPushAsyncTask__articleId:"+articleId);
        if (articleId != null) {

            PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

            //查询文章ID信息，判断是不是用户自己的文章
            ArticleInfo articleInfoInDB = articleInfoService.getArticleDetailInfo(articleId);

            //没有用户信息，相当于是保存平台文章，则进行添加;否则如果是自己的文章，则进行更新
            if (articleInfoInDB.getUserId() != null && articleInfoInDB.getUserId().intValue() == userId.intValue()) {
                log.info("[UserSaveArticleInfoWxPushAsyncTask]__modifyUserArticleInfo");
                ArticleInfo articleInfo = new ArticleInfo();
                articleInfo.setId(articleId);
                articleInfo.setArticleTitle(articleInfoInDB.getArticleTitle());
                articleInfo.setArticleImgUrl(articleInfoInDB.getArticleImgUrl());
                articleInfo.setArticleContent(articleInfoInDB.getArticleContent());
                articleInfo.setArticleVersionNum(articleInfoInDB.getArticleVersionNum());
                articleInfo.setModifyTime(DateUtil.getCurDate());

                articleInfoService.modifyUserArticleInfo(articleInfo);

            } else if (articleInfoInDB.getUserId() == null || (articleInfoInDB.getUserId().intValue() != userId.intValue())) {

                log.info("[UserSaveArticleInfoWxPushAsyncTask]__addUserArticleInfo");
                ArticleInfo articleInfo = new ArticleInfo();
                articleInfo.setArticleTitle(articleInfoInDB.getArticleTitle());
                articleInfo.setArticleImgUrl(articleInfoInDB.getArticleImgUrl());
                articleInfo.setArticleBrandId(articleInfoInDB.getArticleBrandId());
                articleInfo.setArticleTypeId(articleInfoInDB.getArticleTypeId());
                articleInfo.setUserId(userId);
                articleInfo.setArticleSource(3);
                articleInfo.setArticleStatus(1);
                articleInfo.setShareArticleSourceId(articleId);
                articleInfo.setArticleContent(articleInfoInDB.getArticleContent());
                articleInfo.setSpiderProcessStatus(1);
                articleInfo.setArticleVersionNum(articleInfoInDB.getArticleVersionNum());
                articleInfo.setArticleVersionNum(articleInfoInDB.getArticleVersionNum());
                articleInfo.setsType("换成我的");
                articleInfo.setResourceType(articleInfoInDB.getResourceType());//1文章 2视频
                articleInfo.setVideoFormat(articleInfoInDB.getVideoFormat());
                articleInfo.setVideoSize(articleInfoInDB.getVideoSize());
                articleInfo.setVideoUrl(articleInfoInDB.getVideoUrl());
                articleInfo.setArticleDesc(articleInfoInDB.getArticleDesc());//分享配文
                articleInfo.setCreateTime(DateUtil.getCurDate());
                articleInfo.setVideoHeight(articleInfoInDB.getVideoHeight());//视频高度

                articleInfoService.addUserArticleInfo(articleInfo);

                finalArticleId = articleInfo.getId();

            }

//            WxMpKefuMessage.WxArticle wxArticle = new WxMpKefuMessage.WxArticle();
//            wxArticle.setTitle(articleInfoInDB.getArticleTitle());
//            wxArticle.setDescription(articleInfoInDB.getArticleDesc());
//            wxArticle.setPicUrl(articleInfoInDB.getArticleImgUrl());

            //拼接链接地址
            String articleDetailUrl = platformSysInfoConfig.getArticleDetailUrl();
            String accessUrl = articleDetailUrl + finalArticleId;

            if(articleInfoInDB.getResourceType().equals(2)){//如果是视频
                accessUrl=accessUrl.replace("/article/","/video/");
                accessUrl=accessUrl.replace("/detail.html?","/index.html?");
                accessUrl=accessUrl+"&userId="+ userId +"&t=2";
            }

            //wxArticle.setUrl(accessUrl);

            String kefuMsg="文章已添加您的名片\n\n" +
                    "标题：《"+articleInfoInDB.getArticleTitle()+"》\n\n"+
                    //"\uD83D\uDC49<a href='" +accessUrl+ "'>点击领取这篇文章</a>\n\n"+
                    "\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=领取爆文&msgmenuid=+++\">点击领取这篇文章</a>\n\n"+
                    "\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=唤醒小编&msgmenuid=+++\">回复【 9 】查看更多爆文</a>";

            redisCacheUtil.setCacheObject("UPLOAD_TEMP_MSG_PUSH"+ userId,finalArticleId,3600);

            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(userOpenId);

            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
            }

            WxMpKefuMessage messageDay = WxMpKefuMessage.TEXT().toUser(userOpenId).content(kefuMsg).build();

            try {
                weixinService.getKefuService().sendKefuMessage(messageDay);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
    }
}
